package com.example.recordingpen_datacollection.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

import com.example.recordingpen_datacollection.result.exceptionhandler.BusinessException;
import com.example.recordingpen_datacollection.result.exceptionhandler.JWException;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.example.recordingpen_datacollection.result.RLISTconfig.ResultCode.EXC;

@Service
public class SmsService {
     @Autowired
    private Environment env;
     public boolean sendSms(String phoneNumber, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                env.getProperty("aliyun.sms.accessKeyId"),
                env.getProperty("aliyun.sms.accessKeySecret"));
        IAcsClient client = new DefaultAcsClient(profile);
         SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);
        request.setSignName(env.getProperty("aliyun.sms.signName"));
        request.setTemplateCode(env.getProperty("aliyun.sms.templateCode"));
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
         try {
            SendSmsResponse response = client.getAcsResponse(request);
            if (!"OK".equals(response.getCode())) {
                System.err.println("发送短信失败:"+response.getMessage());
                throw new BusinessException(EXC,"Failed to send SMS: " + response.getMessage());
            }
        } catch (ClientException e) {
             System.err.println("发送短信失败--"+e);
            throw new BusinessException(EXC,"Failed to send SMS");
        }
         return true;
    }
}